﻿using Microsoft.Live;
using ShopPowerTemplate.Common;
using ShopPowerTemplate.Common.Authentication;
using ShopPowerTemplate.Entities;
using ShopPowerTemplate.ViewModels;
using ShopPowerTemplate.WebServiceReference;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.ApplicationSettings;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;


// The Grid Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234226

namespace ShopPowerTemplate
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// An overview of the Grid Application design will be linked to in future revisions of
    /// this template.
    /// </summary>
    sealed partial class App : Application
    {
        public static ShoppingCartViewModel ShoppingCart { get; set; }
        public static Customer CurrentCustomer { get; set; }

        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CurrentUICulture;
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            // TODO: Create a data model appropriate for your problem domain to replace the sample data
            //var sampleData = new SampleDataSource();

            if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                //TODO: Load state from previously suspended application
            }

            //Load shopping cart
            ShoppingCart = new ShoppingCartViewModel();

            // Create a Frame to act navigation context and navigate to the first page,
            // configuring the new page by passing required information as a navigation
            // parameter
            var rootFrame = new Frame();
            rootFrame.Navigate(typeof(CategoryViewPage));

            // Place the frame in the current Window and ensure that it is active
            Window.Current.Content = rootFrame;
            Window.Current.Activate();

            // Register search's handle
            Windows.ApplicationModel.Search.SearchPane.GetForCurrentView().QuerySubmitted +=
                (sender, queryArgs) =>
                {
                    SearchResultsPage.Activate(queryArgs.QueryText);
                };

            // Register handler for CommandsRequested events from the settings pane
            SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;

            //Update application tile
            TilesHelper.UpdateTile();
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        void OnSuspending(object sender, SuspendingEventArgs e)
        {
            //TODO: Save application state and stop any background activity
        }

        protected override void OnSearchActivated(Windows.ApplicationModel.Activation.SearchActivatedEventArgs args)
        {
            //ShopPowerTemplate.SearchResultsPage.Activate(args.QueryText);

            // TODO: Move the following code to OnLaunched to speed up searches when your
            //       application is already running:

            //Windows.ApplicationModel.Search.SearchPane.GetForCurrentView().QuerySubmitted +=
            //    (sender, queryArgs) =>
            //    {
            //        ShopPowerTemplate.Views.SearchResultsPage.Activate(queryArgs.QueryText);
            //    };

            // Register handler for CommandsRequested events from the settings pane
            SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;

        }


        void OnCommandsRequested(SettingsPane settingsPane, SettingsPaneCommandsRequestedEventArgs eventArgs)
        {
            UICommandInvokedHandler handler = new UICommandInvokedHandler(OnSettingsCommand);

            // LogOut
            SettingsCommand signOutCommand =
                new SettingsCommand("signOut", "Cerrar sesión", handler);
            eventArgs.Request.ApplicationCommands.Add(signOutCommand);
        }


        void OnSettingsCommand(IUICommand command)
        {
            // Obtenemos en cuál de los Setting ha pulsado el usuario
            SettingsCommand settingsCommand = (SettingsCommand)command;

            // Según el que haya pulsado hacemos unas cosas u otras
            switch ((string)settingsCommand.Id)
            {
                case "signOut":
                    SignOut();
                    break;
            }
        }

        public async static Task<bool> SignIn()
        {
            if (CurrentCustomer == null)
            {
                try
                {
                    var theme = App.Current.RequestedTheme == ApplicationTheme.Light ? ThemeType.Light : ThemeType.Default;
                    LiveAuthClient authClient = new LiveAuthClient { Theme = theme };
                    LiveLoginResult authResult = await authClient.LoginAsync(new List<string>() { "wl.signin", "wl.emails" });

                    if (authResult.Status == LiveConnectSessionStatus.Connected)
                    {
                        string liveToken = authResult.Session.AccessToken;

                        WebServiceClient service = new WebServiceClient();
                        CurrentCustomer = await service.RegisterUserIfNecessaryAsync(liveToken);
                    }
                }
                catch (Exception ex)
                {
                    ExceptionsHelper.ShowFatalError(ex.Message, null);
                }
            }

            return CurrentCustomer != null;
        }

        public static void SignOut()
        {
            try
            {
                var theme = App.Current.RequestedTheme == ApplicationTheme.Light ? ThemeType.Light : ThemeType.Default;
                LiveAuthClient authClient = new LiveAuthClient { Theme = theme };
                if (authClient.CanLogout) authClient.Logout();

                CurrentCustomer = null;
            }
            catch (Exception ex)
            {
                ExceptionsHelper.ShowFatalError(ex.Message, null);
            }
        }
    }
}
